import router from "@/router";
import ACCESS_ENUM from "@/access/accessEnum";
import store from "@/store";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
  await store.dispatch("user/refreshLoginUser");
  const loginUser = store.state.user.loginUser;
  /**
   * 如果页面不需要登录，或者角色匹配直接放行
   */
  if (checkAccess(loginUser, to.meta?.access as string)) {
    next();
    return;
  }
  /**
   * 未登录，跳转到登录页面
   */

  if (!loginUser.userRole) {
    console.log("来了", store.state.user.loginUser);
    next("/user/login");
    return;
  }
  /**
   * 判断页面是否需要管理员权限
   */
  if (to.meta?.access === ACCESS_ENUM.ADMIN) {
    if (loginUser?.userRole !== ACCESS_ENUM.ADMIN) {
      next("/noAuth");
      return;
    }
  }
  next();
});
